package org.jobtask.schedule;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import org.jobtask.io.JobIO;

public class TaskGroup implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 8997792937032874869L;
	private LinkedHashMap<KeyValue,List<JobTask>> taskGroup;
	
	public TaskGroup()
	{
		taskGroup=new LinkedHashMap<KeyValue, List<JobTask>>();
	}
	
//	public void reset(){
//		KeyValue[] kvs=this.getGroups();
//		for(int index=0;index<kvs.length;index++){
//			List<JobTask> list=this.taskGroup.get(kvs[index]);
//			for(int count=0;count<list.size();index++){
//				list.get(index).reset();
//			}
//		}
//	}
	
	public KeyValue[] getGroups(){
		 Object[] obj=this.taskGroup.keySet().toArray();
		 KeyValue[] kv=new KeyValue[obj.length];
	      for(int index=0;index<obj.length;index++){
	    	  	kv[index]=(KeyValue)obj[index];
	      }
	      return kv;
	}
	
	public List<JobTask> getGroupItems(KeyValue key){
		return this.taskGroup.get(key);
	}
	
	public boolean addGroup(KeyValue group){
		boolean isOK=!this.taskGroup.containsKey(group);
		if(isOK){
		    this.taskGroup.put(group, new ArrayList<JobTask>());
		}
		return isOK;
	}
	
	public boolean addGroup(KeyValue group,List<JobTask> list){
		boolean isOK=!this.taskGroup.containsKey(group);
		if(isOK){
			this.taskGroup.put(group,list);
		}
		return isOK;
	}
	
	public void renameGroup(KeyValue group){
		for(KeyValue kv:this.getGroups()){
			if(kv.getKey().equals(group.getKey())){
				kv.setValue(group.getValue());
				break;
			}
		}
	}
	
	public void removeGroup(KeyValue group){
		boolean isOK=!this.taskGroup.containsKey(group);
		if(isOK){
		    this.taskGroup.remove(group);
		}
	}
	
	public void addGroupItem(KeyValue group,JobTask jt){
		this.taskGroup.get(group).add(jt);
	}
	
	public void removeGroupItem(KeyValue group,int index){
		this.taskGroup.get(group).remove(index);
		
	}
	
	public int getGroupTotal(){
		int count=0;
		for(Iterator<List<JobTask>> iter=this.taskGroup.values().iterator();iter.hasNext();){
			 List list=iter.next();
			 count+=list.size();
		}
		return count;
	}
	
	public Object[] getFullTask(){
		ArrayList<KeyValue> list=new ArrayList<KeyValue>();
		KeyValue[] kv=this.getGroups();
		for(int index=0;index<kv.length;index++){
			for(Iterator<JobTask> iter=this.getGroupItems(kv[index]).iterator();iter.hasNext();){
				JobTask job=iter.next();
				KeyValue kk=new KeyValue(job.getSequece(),"<"+kv[index].getValue()+"> "+job.getTaskName());
				list.add(kk);
			}
		}
		return  list.toArray();
	}
	
}
